package cn.tedu.boot021.controller;

import cn.tedu.boot021.entity.Product;
import cn.tedu.boot021.utils.DBUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@RestController
public class ProductController {
    @RequestMapping("/insert")
    public String insert(Product product){

        try (Connection conn = DBUtil.getConnection()){
            String sql = "INSERT INTO product VALUES(NULL,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,product.getTitle());
            ps.setDouble(2,product.getPrice());
            ps.setInt(3,product.getNum());
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "添加完成!<a href='/'>返回首页</a>";
    }
    @RequestMapping("/select")
    public String select(){
        ArrayList<Product> list = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection()){
            String sql = "SELECT id,title,price,num FROM product";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while(rs.next()){
                Product p = new Product();
                p.setId(rs.getInt(1));
                p.setTitle(rs.getString(2));
                p.setPrice(rs.getDouble(3));
                p.setNum(rs.getInt(4));
                list.add(p);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list.toString();
    }
}
